import { defineConfig } from 'vitepress'
import { withMermaid } from 'vitepress-plugin-mermaid'
import { examplePlugin, demoPlugin, mermaidViewerPlugin } from './plugins/mdPlugin'
import { component, DEMO_DIR } from './plugins/vitePlugin'
import { readdirSync, readFileSync, rmSync } from 'fs'
import { resolve } from 'path'

/**
 * @description: 获取资源绝对路径
 */
function getAbsolutePath(...paths: string[]) {
  return resolve(__dirname, '..', 'src', ...paths)
}

/**
 * @description: 获取路径下指定后缀文件名
 * @param {string} path - 路径
 * @param {string} ext - 扩展名
 */
function getDir(path: string, ext: string) {
  const match = new RegExp(`.${ext}$`)
  const absolutePath = getAbsolutePath(path)
  return readdirSync(absolutePath)
    .filter(file => match.test(file))
    .sort((a, b) => a.localeCompare(b, 'zh'))
}

/**
 * @description: 或者侧边栏配置
 * @param {string} path - 路径
 * @param {string} ext - 扩展名
 */
function getSideBar(path: string, ext: string) {
  const MATCH_TITLE = /^#\W(.*)/
  const MATCH_FILENAME = /(.*)\.\w*$/
  const files = getDir(path, ext)
  const sidebar = []

  for (const file of files) {
    const content = readFileSync(getAbsolutePath(path, file), 'utf-8')
    const lines = content.split('\n')
    const findTitle = lines.find(line => MATCH_TITLE.test(line))
    const title = MATCH_TITLE.exec(findTitle || '')?.[1]
    const fileName = MATCH_FILENAME.exec(file)?.[1]
    sidebar.push({ text: /* title ||  */ fileName, link: `/${path}/${fileName}` })
  }

  return sidebar
}

export const vitepressConfig = defineConfig({
  lastUpdated: true,
  lang: 'zh-CN',
  title: '梦渊笔记',
  description: '心有所向，日复一日，必有精进',
  srcDir: 'src',
  outDir: 'dist',
  cacheDir: './.vitepress/.cache',
  markdown: { config: md => (examplePlugin(md), demoPlugin(md), mermaidViewerPlugin(md)) },
  themeConfig: {
    nav: [
      { text: '首页', link: '/' },
      {
        text: '前端',
        items: [
          { text: 'html', link: '/html/script' },
          { text: 'css', link: '/css/scss' },
          { text: 'js', link: '/js/简介' },
          { text: 'ts', link: '/ts/简介' },
          { text: 'vue', link: '/vue/概述' },
          { text: 'node', link: '/node/缓冲区' },
          { text: 'bpmnjs', link: '/bpmnjs/base' },
          { text: '工程化', link: '/engineering/webpack' },
          { text: '浏览器', link: '/browser/跨域' },
          { text: '典型案例', link: '/typical-case/图片懒加载' },
          { text: '开发记录', link: '/record/dev' }
        ]
      },
      { text: '后端', items: [] },
      {
        text: '通用',
        items: [
          { text: 'git', link: '/git/简介' },
          { text: '网络', link: '/network/CDN' },
          { text: '算法', link: '/algorithm/质数' }
        ]
      }
    ],
    sidebar: {
      '/html/': [{ text: 'html', items: getSideBar('html', 'md') }],
      '/css/': [{ text: 'css', items: getSideBar('css', 'md') }],
      '/js/': [{ text: 'js', items: getSideBar('js', 'md') }],
      '/ts/': [{ text: 'ts', items: getSideBar('ts', 'md') }],
      '/git/': [{ text: 'git', items: getSideBar('git', 'md') }],
      '/vue/': [{ text: 'vue', items: getSideBar('vue', 'md') }],
      '/bpmnjs/': [{ text: 'bpmnjs', items: getSideBar('bpmnjs', 'md') }],
      '/network/': [{ text: '网络', items: getSideBar('network', 'md') }],
      '/browser/': [{ text: '浏览器', items: getSideBar('browser', 'md') }],
      '/engineering/': [{ text: '工程化', items: getSideBar('engineering', 'md') }],
      '/record/': [{ text: '记录', items: getSideBar('record', 'md') }],
      '/typical-case/': [{ text: '案例', items: getSideBar('typical-case', 'md') }],
      '/algorithm/': [{ text: '算法', items: getSideBar('algorithm', 'md') }],
      '/node/': [{ text: '算法', items: getSideBar('node', 'md') }],
    }
  },
  vite: {
    server: {
      host: '0.0.0.0'
    },
    define: {
      __VUE_OPTIONS_API__: false
    },
    resolve: {
      alias: {
        '@': resolve(__dirname, '..', 'src'),
        '@demo': resolve(__dirname, '..', DEMO_DIR)
      }
    },
    plugins: [component()]
  },

  buildEnd: () => rmSync(DEMO_DIR, { recursive: true })
})

export default withMermaid(vitepressConfig)
